package ioc

import (
	"context"
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"strings"
	"webook/internal/web"
	"webook/internal/web/middleware"
	"webook/pkg/ginx/middleware/ratelimit"
	"webook/pkg/logx"
	ratelimit2 "webook/pkg/ratelimit"
)

func InitWebServer(middlewares []gin.HandlerFunc, uh *web.UserHandler, wh *web.Oauth2WechatHandler, ah *web.ArticleHandler) *gin.Engine {
	server := gin.Default()
	server.Use(middlewares...)
	uh.RegisterRoutes(server)
	wh.RegisterRoutes(server)
	ah.RegisterRoutes(server)
	return server
}

func InitMiddlewares(limiter ratelimit2.RateLimiter, jwtHdl web.IJwtHandler, logger logx.LoggerX) []gin.HandlerFunc {
	return []gin.HandlerFunc{
		// 限流中间件
		ratelimit.
			NewBuilder(limiter).
			Build(),
		// 跨域中间件
		cors.New(cors.Config{
			AllowCredentials: true,                                       // 允许携带cookie
			AllowHeaders:     []string{"Content-Type", "authorization"},  // 请求头
			AllowMethods:     []string{"POST"},                           // 请求方法
			ExposeHeaders:    []string{"x-jwt-token", "x-refresh-token"}, // 允许前端获取的请求头信息
			AllowOriginFunc: func(origin string) bool {
				return strings.HasPrefix(origin, "http://localhost")
			},
		}),
		// 登录中间件
		middleware.NewLoginMiddlewareBuilder(jwtHdl).
			IgnorePath("/users/login").
			IgnorePath("/users/signup").
			IgnorePath("/users/code/sms/send").
			IgnorePath("/users/code/sms/verify").
			IgnorePath("/oauth2/wechat/authurl").
			IgnorePath("/users/refresh_token").
			BuildByJWT(),
		// 	日志中间件
		middleware.NewLogMiddlewareBuilder(func(context context.Context, al middleware.AccessLog) {
			logger.Info("处理HTTP请求与响应", logx.Field{
				Key:   "accessLog",
				Value: al,
			})
		}).
			AllowReqBody().
			AllowRespBody().
			Build(),
	}
}
